// InputStream.cpp: implementation of the InputStream class.
//
//////////////////////////////////////////////////////////////////////

#include "InputStream.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

InputStream::InputStream()
{

}

InputStream::~InputStream()
{

}

unsigned int InputStream::read(Mensaje &data){
	unsigned int length;
	if (csocket != INVALID_SOCKET) { /* La conexion esta activa */
			int result = recv(csocket,reinterpret_cast<char*>(&length),sizeof(length),0);
		//tamanio total de toda la estructura
		if ((result <sizeof(length)) || (result<0)){
			IOException* ex = new IOException();
			throw ex;
		}
		result = recv(csocket,reinterpret_cast<char*>(&data),length,0);

		if ((result < length ) || (result<0)){
			IOException ex;
			throw ex;
		}
		return length;
    } else { /* La conexion no esta activa */
		IOException* ex = new IOException();
		throw ex;
    }
	
}

unsigned int InputStream::read(char* data,unsigned int length){
	if (csocket != INVALID_SOCKET) { /* La conexion esta activa */
		int result = recv(csocket,data,length,0);//recibir(data,length);
		while((result > 0)&&(result < length )){
			data+=result;
			length-=result;
			//Sleep(150);
			result = recv(csocket,data,length,0);
		}
		if ((csocket != INVALID_SOCKET)&&(result == -1)){
			IOException* ex = new IOException("ERROR AL RECIBIR DATOS POR SOCKET (Se perdio la conexion)",csocket);
			closesocket(csocket);
			throw ex;
		}
		//tamanio total de toda la estructura
		return 0;
    } else { /* La conexion no esta activa */
		IOException* ex = new IOException("ERROR AL RECIBIR DATOS POR SOCKET (Se perdio la conexion)",csocket);
		closesocket(csocket);
		throw ex;
    }
}

void InputStream::recibir(char* data,unsigned int length){
	int result = recv(csocket,data,length,0);
	while (result == -1){
		if (csocket != INVALID_SOCKET){
			result = recv(csocket,data,length,0);
		} else {
			IOException ex("ERROR AL RECIBIR DATOS POR SOCKET (Se perdio la conexion)",csocket);
			closesocket(csocket);
			throw ex;
		}
	}
}